
from PyQt4.QtGui import QTableView, QApplication, QAction
from PyQt4.QtCore import Qt, QAbstractTableModel, QVariant, SIGNAL, QModelIndex, pyqtSignature, SLOT
from SimpleCells.Components.Table.SCTableViewTools import *

try:
    from numpy import ndarray, dtype
except ImportError:
    ndarray, dtype = None, None

class SCArrayModel(QAbstractTableModel):
    
    def __init__(self,data,parent=None):
        QAbstractTableModel.__init__(self,parent)
        assert data.dtype in (dtype('int32'),dtype('float64'))
        self.__data = data
        self.__dtype = data.dtype

    def getData(self):
        return self.__data
    
    def rowCount(self,parent=QModelIndex()):
        return self.__data.shape[0]
    
    def columnCount(self,parent=QModelIndex()):
        if self.__im2D__():
            return self.__data.shape[1]
        return 1
    
    def __im2D__(self):
        return (len(self.__data.shape) == 2)
    
    def headerData(self,section,orientation,role = Qt.DisplayRole):
        if role == Qt.DisplayRole:
            return QVariant(int(section))
        return QVariant()
    
    def recordData(self,index,value):
        if not index.isValid():
            return False
        val, ok = None, False
        if self.__dtype == dtype('int32'):
            val, ok = value.toInt()
        elif self.__dtype == dtype('float64'):
            val, ok = value.toDouble()
        if not ok: 
            return False
        if self.__im2D__():
            self.__data[index.row(),index.column()] = val
            return True
        else:
            self.__data[index.row()] = val
            return True
        return False
    
    def getCell(self, index):
        if self.__im2D__():
            return self.__data[index.row(),index.column()]
        return self.__data[index.row()]

    def setData(self, index, value, role=Qt.EditRole):
        if not index.isValid():
            return False
        if role == Qt.EditRole and self.recordData(index,value):
            self.emit(SIGNAL("dataChanged(QModelIndex,QModelIndex)"),index,index)
            return True
        return False
    
    def data(self,index, role=Qt.DisplayRole):
        if not index.isValid():
            return QVariant()
        if role == Qt.DisplayRole:
            if self.__dtype == dtype('int32'):
                return QVariant('%d' % self.getCell(index))
            elif self.__dtype == dtype('float64'):
                return QVariant('%.5f' % self.getCell(index))
        elif role == Qt.TextAlignmentRole:
            return QVariant(int(Qt.AlignRight|Qt.AlignVCenter))            
        elif role == Qt.EditRole or role == Qt.ToolTipRole:
            return QVariant(repr(self.getCell(index)))
        return QVariant()
    
    def flags(self, index):
        if index.isValid():
            return Qt.ItemFlags(QAbstractTableModel.flags(self, index)|\
                                Qt.ItemIsEditable)

class SCArrayView(QTableView):
    def __init__(self,parent=None):
        QTableView.__init__(self,parent)
        self.actionCopy = QAction("copy",self)
        self.addActions([self.actionCopy])
        self.setupConnects()
    
    def setupConnects(self):
        self.connect(self.actionCopy,SIGNAL("triggered()"),self,SLOT("copy()"))

    @pyqtSignature("")
    def copy(self):
        var = SCTableReadTools.selectionToText(self)
        clipboard = QApplication.clipboard()
        clipboard.setText(var)
